/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainCliente.java
 *
 * Created on 15/06/2011, 23:55:06
 */
package gui.cliente;


import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;

import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListModel;
import javax.swing.SwingUtilities;

import base.Util;
import base.audio.AudioManager;
import base.audio.AudioSocket;
import base.transporte.SRConnector;
import base.transporte.SRPacket;
import base.transporte.SRSocket;

import negocio.beans.Usuario;
import negocio.cliente.FachadaCliente;
import negocio.cliente.negocio.Controle;
import negocio.cliente.negocio.EnviadorArquivo;
import negocio.servidor.FachadaServidor;

/**
 * 
 * @author Eduardo
 */
public class InicioCliente extends javax.swing.JFrame {

	LoginCliente janelaLogin;
	AtualizadorDaLista atualizadorLista;

	/** Creates new form MainCliente */
	public InicioCliente(LoginCliente janelaCliente) {
		this.janelaLogin = janelaCliente;
		initComponents();
		atualizadorLista = new AtualizadorDaLista();
		atualizadorLista.start();
		
		ArrayList<Usuario> novaLista = FachadaCliente.getInstance().getAmigosPendentes();
		
		for (Usuario amigo : novaLista) {
			int opt = JOptionPane.showConfirmDialog(this, "Deseja adicionar " + amigo.getLogin() + "?", "Pedido de amizade", JOptionPane.YES_NO_OPTION);
			if(opt == JOptionPane.YES_OPTION){
				FachadaCliente.getInstance().aprovarAmizade(amigo);
			}else{
				FachadaCliente.getInstance().recusarPedidoAmizade(amigo, false);
			}
		}

	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed"
	// desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {

		jPanel2 = new BackgroundPanel2();
		jLabel2 = new javax.swing.JLabel();
		jComboBox1 = new javax.swing.JComboBox();
		jLabel1 = new javax.swing.JLabel();
		jPanel3 = new BackgroundPanel3();
		jButton1 = new javax.swing.JButton();
		jButton2 = new javax.swing.JButton();
		jScrollPane1 = new javax.swing.JScrollPane();
		jList1 = new javax.swing.JList();
		jButton3 = new javax.swing.JButton();
		jButton4 = new javax.swing.JButton();
		jLabel3 = new javax.swing.JLabel();
		jButton5 = new javax.swing.JButton();
		jPanel1 = new BackgroundPanel5();
		jMenuBar1 = new javax.swing.JMenuBar();
		Arquivo = new javax.swing.JMenu();
		jMenuItem1 = new javax.swing.JMenuItem();
		jMenu3 = new javax.swing.JMenu();
		jMenu1 = new javax.swing.JMenu();
		jMenuItem2 = new javax.swing.JMenuItem();
		jMenu2 = new javax.swing.JMenu();
		jMenuItem5 = new javax.swing.JMenuItem();

		setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
		setTitle("[SKY-PE]");
		addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowClosed(java.awt.event.WindowEvent evt) {
				atualizadorLista.stop();
				formWindowClosed(evt);
			}
		});

		jPanel2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
		jPanel2.setMaximumSize(new java.awt.Dimension(32767, 110));

		jLabel2.setFont(new java.awt.Font("SansSerif", 1, 36)); // NOI18N
		jLabel2.setForeground(new java.awt.Color(255, 255, 255));
		jLabel2.setText(FachadaCliente.getInstance().getUsuarioLocal().toString());

		jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Online", "Ocupado", "Ausente" }));
		jComboBox1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jComboBox1ActionPerformed(evt);
			}
		});

		javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
		jPanel2.setLayout(jPanel2Layout);
		jPanel2Layout.setHorizontalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				jPanel2Layout
						.createSequentialGroup()
						.addGroup(
								jPanel2Layout
										.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
										.addGroup(jPanel2Layout.createSequentialGroup().addGap(18, 18, 18).addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 486, Short.MAX_VALUE))
										.addGroup(
												jPanel2Layout.createSequentialGroup().addGap(32, 32, 32)
														.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)))
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jLabel1).addGap(45, 45, 45)));
		jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						jPanel2Layout
								.createSequentialGroup()
								.addGap(23, 23, 23)
								.addGroup(
										jPanel2Layout
												.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
												.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE)
												.addGroup(
														jPanel2Layout
																.createSequentialGroup()
																.addComponent(jLabel2)
																.addGap(37, 37, 37)
																.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
																		javax.swing.GroupLayout.PREFERRED_SIZE))).addContainerGap()));

		jPanel3.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
		jPanel3.setMaximumSize(new java.awt.Dimension(40000, 40000));

		jButton1.setText("Deletar Contato");
		jButton1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton1ActionPerformed(evt);
			}
		});
		jButton1.addKeyListener(new java.awt.event.KeyAdapter() {
			public void keyPressed(java.awt.event.KeyEvent evt) {
				jButton1KeyPressed(evt);
			}
		});

		jButton2.setText("Bloquear Contato");
		jButton2.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton2ActionPerformed(evt);
			}
		});
		jButton2.addKeyListener(new java.awt.event.KeyAdapter() {
			public void keyPressed(java.awt.event.KeyEvent evt) {
				jButton2KeyPressed(evt);
			}
		});

		unsortedModel = new DefaultListModel();
		sortedModel = new SortedListModel(unsortedModel);

		jList1.setModel(sortedModel);
		jList1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
		jList1.setMaximumSize(new java.awt.Dimension(800, 600));
		jList1.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				jList1MouseClicked(evt);
			}
		});
		jScrollPane1.setViewportView(jList1);

		jButton3.setText("Iniciar Chat");
		jButton3.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton3ActionPerformed(evt);
			}
		});
		jButton3.addKeyListener(new java.awt.event.KeyAdapter() {
			public void keyPressed(java.awt.event.KeyEvent evt) {
				jButton3KeyPressed(evt);
			}
		});

		jButton4.setText("Enviar Arquivo");
		jButton4.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton4ActionPerformed(evt);
			}
		});
		jButton4.addKeyListener(new java.awt.event.KeyAdapter() {
			public void keyPressed(java.awt.event.KeyEvent evt) {
				jButton4KeyPressed(evt);
			}
		});

		jLabel3.setFont(new java.awt.Font("Verdana", 1, 18)); // NOI18N
		jLabel3.setForeground(new java.awt.Color(255, 255, 255));
		jLabel3.setText("Contatos");

		jButton5.setText("Ligar");
		jButton5.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton5ActionPerformed(evt);
			}
		});
		jButton5.addKeyListener(new java.awt.event.KeyAdapter() {
			public void keyPressed(java.awt.event.KeyEvent evt) {
				jButton5KeyPressed(evt);
			}
		});

		javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
		jPanel3.setLayout(jPanel3Layout);
		jPanel3Layout.setHorizontalGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				javax.swing.GroupLayout.Alignment.TRAILING,
				jPanel3Layout
						.createSequentialGroup()
						.addGroup(
								jPanel3Layout
										.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
										.addGroup(javax.swing.GroupLayout.Alignment.LEADING,
												jPanel3Layout.createSequentialGroup().addContainerGap().addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 541, Short.MAX_VALUE))
										.addGroup(
												javax.swing.GroupLayout.Alignment.LEADING,
												jPanel3Layout
														.createSequentialGroup()
														.addGap(129, 129, 129)
														.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
														.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
														.addGroup(
																jPanel3Layout
																		.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
																		.addGroup(
																				jPanel3Layout.createSequentialGroup()
																						.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
																						.addGap(10, 10, 10).addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, 132, Short.MAX_VALUE))
																		.addGroup(
																				jPanel3Layout.createSequentialGroup()
																						.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
																						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																						.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE))))
										.addGroup(
												javax.swing.GroupLayout.Alignment.LEADING,
												jPanel3Layout.createSequentialGroup().addContainerGap()
														.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))).addContainerGap()));
		jPanel3Layout.setVerticalGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				javax.swing.GroupLayout.Alignment.TRAILING,
				jPanel3Layout.createSequentialGroup().addContainerGap().addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jButton3).addComponent(jButton2).addComponent(jButton1))
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
						.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jButton5).addComponent(jButton4)).addContainerGap()));

		javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
		jPanel1.setLayout(jPanel1Layout);
		jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 581, Short.MAX_VALUE));
		jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 543, Short.MAX_VALUE));

		Arquivo.setText("Arquivo");

		jMenuItem1.setText("Deslogar");
		jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jMenuItem1ActionPerformed(evt);
			}
		});
		Arquivo.add(jMenuItem1);

		jMenuBar1.add(Arquivo);

		jMenu3.setText("Contatos");
		jMenu3.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

		jMenu1.setText("Gerenciar Contatos");

		jMenuItem2.setText("Adicionar Contatos");
		jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jMenuItem2ActionPerformed(evt);
			}
		});
		jMenu1.add(jMenuItem2);

		jMenu3.add(jMenu1);

		jMenuBar1.add(jMenu3);

		jMenu2.setText("Perfil");

		jMenuItem5.setText("Mudar Nick");
		jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jMenuItem5ActionPerformed(evt);
			}
		});
		jMenu2.add(jMenuItem5);

		jMenuBar1.add(jMenu2);

		setJMenuBar(jMenuBar1);

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
												.addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
														Short.MAX_VALUE)
												.addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
														Short.MAX_VALUE)).addContainerGap())
				.addGroup(
						layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
								Short.MAX_VALUE)));
		layout.setVerticalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup().addContainerGap()
								.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addGap(18, 18, 18)
								.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addContainerGap())
				.addGroup(
						layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE,
								javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

		pack();
	}// </editor-fold>//GEN-END:initComponents

	private void formWindowClosed(java.awt.event.WindowEvent evt) {// GEN-FIRST:event_formWindowClosed
		// TODO add your handling code here:
		FachadaCliente.getInstance().deslogar();
		janelaLogin.setVisible(true);
	}// GEN-LAST:event_formWindowClosed

	private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jMenuItem1ActionPerformed
		// TODO add your handling code here:
		this.dispose();
	}// GEN-LAST:event_jMenuItem1ActionPerformed

	private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jMenuItem2ActionPerformed
		// TODO add your handling code here:
		AdicionarContato adicionar = new AdicionarContato();

		adicionar.setLocationRelativeTo(this);
		adicionar.setVisible(true);
	}// GEN-LAST:event_jMenuItem2ActionPerformed

	private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton3ActionPerformed
		// TODO add your handling code here:
		Usuario amigoChat = (Usuario) this.jList1.getSelectedValue();

		ChatCliente chat = new ChatCliente(amigoChat);

		chat.setLocationRelativeTo(this);
		chat.setVisible(true);
	}// GEN-LAST:event_jButton3ActionPerformed

	private void jButton3KeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_jButton3KeyPressed
		// TODO add your handling code here:
		if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
			Usuario amigoChat = (Usuario) this.jList1.getSelectedValue();

			ChatCliente chat = new ChatCliente(amigoChat);

			chat.setLocationRelativeTo(this);
			chat.setVisible(true);
		}
	}// GEN-LAST:event_jButton3KeyPressed

	private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jMenuItem5ActionPerformed
		// TODO add your handling code here:
		// mudar nick
	}// GEN-LAST:event_jMenuItem5ActionPerformed

	private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jComboBox1ActionPerformed
		// TODO add your handling code here:
		// atualizar status
	}// GEN-LAST:event_jComboBox1ActionPerformed

	private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton2ActionPerformed
		// TODO add your handling code here:
		// bloquear contato
	}// GEN-LAST:event_jButton2ActionPerformed

	private void jButton2KeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_jButton2KeyPressed
		// TODO add your handling code here:
		if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
			// bloquear contato
		}
	}// GEN-LAST:event_jButton2KeyPressed

	private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton1ActionPerformed
		// TODO add your handling code here:
		// deletar contato
	}// GEN-LAST:event_jButton1ActionPerformed

	private void jButton1KeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_jButton1KeyPressed
		// TODO add your handling code here:
		if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
			// deletar contato
		}
	}// GEN-LAST:event_jButton1KeyPressed

	private void jList1MouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_jList1MouseClicked
		// TODO add your handling code here:
		if (evt.getClickCount() == 2) {
			Usuario amigoChat = (Usuario) this.jList1.getSelectedValue();

			ChatCliente chat = new ChatCliente(amigoChat);

			chat.setLocationRelativeTo(this);
			chat.setVisible(true);
		}
	}// GEN-LAST:event_jList1MouseClicked

	private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton4ActionPerformed
		// TODO add your handling code here:
		Usuario amigoChat = (Usuario) this.jList1.getSelectedValue();

		enviarArquivo(amigoChat);
	}// GEN-LAST:event_jButton4ActionPerformed

	private void jButton4KeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_jButton4KeyPressed
		// TODO add your handling code here:
		if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
			Usuario amigoChat = (Usuario) this.jList1.getSelectedValue();

			enviarArquivo(amigoChat);
		}
	}// GEN-LAST:event_jButton4KeyPressed

	class EnviadorThread implements Runnable{
		EnviadorArquivo enviador;
		
		public EnviadorThread(EnviadorArquivo enviador) {
			// TODO Auto-generated constructor stub
			this.enviador = enviador;
		}
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			enviador.enviarArquivo();
			
		}
	}
	private void enviarArquivo(Usuario user){
		JFileChooser fileChooser = new JFileChooser(".");
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		int opc = fileChooser.showOpenDialog(this);
		InetAddress ip = null;
		try {
			ip = InetAddress.getByAddress(Util.intToBytes(user.getIp()));
			if(ip.equals(InetAddress.getByName("localhost"))){
				ip = FachadaCliente.getInstance().getEnderecoServidor();
			}
		} catch (UnknownHostException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		if (opc == JFileChooser.APPROVE_OPTION) {
			File file = fileChooser.getSelectedFile();
			EnviadorArquivo enviador = null;
			
				enviador = new EnviadorArquivo(file, ip);
			
			new Thread(new EnviadorThread(enviador)).start();
			
		}
	}
	
	private void jButton5KeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_jButton5KeyPressed
		// TODO add your handling code here:
		if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
			iniciarAudio();
		}
	}// GEN-LAST:event_jButton5KeyPressed

	private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton5ActionPerformed
		// TODO add your handling code here:

		iniciarAudio();

	}// GEN-LAST:event_jButton5ActionPerformed

	
	private void iniciarAudio(){
		Object obj = this.jList1.getSelectedValue();
		Usuario usuario = (Usuario) obj;
		PopOutAudio audio = new PopOutAudio();
		InetAddress ip = null;
		try {
			ip = InetAddress.getByAddress(Util.intToBytes(usuario.getIp()));
			if(ip.equals(InetAddress.getByName("localhost"))){
				ip = FachadaCliente.getInstance().getEnderecoServidor();
			}
		} catch (UnknownHostException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		SRConnector conector = new  SRConnector(ip, 42000 , "Conexao Audio");
		try {
			SRSocket skt = conector.abrirConexao();
			skt.enviarPacote(new SRPacket(0, "INICIAR_CONVERSA_AUDIO".getBytes()));
			String resposta = new String(skt.receberPacote().getData());
			System.out.println(resposta);
			if(resposta.equals("SUCESSO")){
				Controle controle = FachadaCliente.getInstance().getControle();
				AudioSocket audio_socket = new AudioSocket(ip, 50000, 50000);
				AudioManager audio_manager = new AudioManager(audio_socket);
				audio_manager.start();
				controle.setAudio_socket(audio_socket);
			} else {
				JOptionPane.showMessageDialog(this, resposta);
			}
		} catch (SocketTimeoutException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		audio.setNome(usuario.getLogin());
		audio.setLocationRelativeTo(this);
		audio.setVisible(true);
	}
	
	/**
	 * @param args
	 *            the command line arguments
	 */

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JMenu Arquivo;
	private javax.swing.JButton jButton1;
	private javax.swing.JButton jButton2;
	private javax.swing.JButton jButton3;
	private javax.swing.JButton jButton4;
	private javax.swing.JButton jButton5;
	private javax.swing.JComboBox jComboBox1;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JLabel jLabel2;
	private javax.swing.JLabel jLabel3;
	private javax.swing.JList jList1;
	private javax.swing.JMenu jMenu1;
	private javax.swing.JMenu jMenu2;
	private javax.swing.JMenu jMenu3;
	private javax.swing.JMenuBar jMenuBar1;
	private javax.swing.JMenuItem jMenuItem1;
	private javax.swing.JMenuItem jMenuItem2;
	private javax.swing.JMenuItem jMenuItem5;
	private javax.swing.JPanel jPanel1;
	private javax.swing.JPanel jPanel2;
	private javax.swing.JPanel jPanel3;
	private javax.swing.JScrollPane jScrollPane1;

	private SortedListModel sortedModel;
	private DefaultListModel unsortedModel;

	// End of variables declaration//GEN-END:variables

	private class AtualizadorDaLista implements Runnable {

		private boolean running;
		private FachadaCliente fachada;

		public AtualizadorDaLista() {
			fachada = FachadaCliente.getInstance();
			running = true;
		}

		public void start() {
			Thread th = (new Thread(this));
			th.setPriority(Thread.MIN_PRIORITY);
			th.start();
		}

		public void stop() {
			running = false;
		}

		@Override
		public void run() {
			while (running) {

				try {
					SwingUtilities.invokeLater(new Runnable() {

						@Override
						public void run() {
							ArrayList<Usuario> novaLista = fachada.getAmigos();
							// System.out.println(novaLista);
							for (Object amigo : unsortedModel.toArray()) {
								if (!novaLista.contains((Usuario) amigo)) {
									// System.out.println("Removendo Usuario");
									unsortedModel.removeElement(amigo);
								}
							}

							for (Usuario amigo : novaLista) {
								int indice = unsortedModel.indexOf(amigo);
								if (indice != -1) {
									unsortedModel.set(indice, amigo);
									// System.out.println("Atualizando usuario");
								} else {
									// System.out.println("Adicionando usuario");
									unsortedModel.addElement(amigo);
								}
							}
						}
					});

					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
